from random import Random
import hashlib


# 获取由4位随机大小写字母、数字组成的salt值
def create_salt(length: int = 4) -> str:
    salt = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789+-*'
    len_chars = len(chars) - 1
    random = Random()
    for i in range(length):
        # 每次从chars中随机取一位
        salt += chars[random.randint(0, len_chars)]
    return salt


# 获取原始密码+salt的md5值
# salt参数留空（""），就可以不加盐
def create_salty_md5(pwd: str, salt: str) -> str:
    md5_obj = hashlib.md5()
    md5_obj.update((pwd + salt).encode("utf-8"))
    return md5_obj.hexdigest()


def create_md5(data: str = "") -> str:
    md5_obj = hashlib.md5()
    md5_obj.update(data.encode("utf-8"))
    return md5_obj.hexdigest()


if __name__ == "__main__":
    text = "helloworld"
    md5 = create_salty_md5(text, create_salt())
    print(f"[myMD5.py][main]加盐加密后的数据为{md5}")
